package com.android.fragmentdemo.thread17

import org.junit.Test

class Demo17 {
    @Test
    fun testRunnable() {
        val th1 = DemoThread()
        th1.name = "th1"
        val th2 = DemoThread()
        th2.name = "th2"
        val th3 = DemoThread()
        th3.name = "th3"

        th1.start()
        th2.start()
        th3.start()

        Thread.sleep(3 * 1000)
    }

    class DemoThread : Thread() {
        override fun run() {
            super.run()
            for (i in 0..4) {
                val value = local.get()
                local.set((value ?: 0) + 1)
                println("${currentThread().name}--value:${local.get()}")
            }
            //remove()方法防止内存泄漏
            local.remove()
        }
    }

    companion object {
        //ThreadLocal为每个使用该变量的线程提供独立的变量副本，所以每个线程都可以独立地改变自己的副本，而不影响其它线程所对应的副本。
        private val local = object : ThreadLocal<Int>() {
            override fun initialValue(): Int {
                return 0
            }
        }
    }

}